package model

import (
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
	"user_srv/global"
	"user_srv/pkg"
)

// 用户表
type User struct {
	gorm.Model
	Mobile   string `gorm:"column:mobile;type:char(11);not null;comment:手机号"`
	Password string `gorm:"column:password;type:varchar(150);not null;comment:密码"`
	NickName string `gorm:"column:nick_name;type:varchar(50);not null;comment:昵称"`
	BirthDay string `gorm:"column:birth_day;type:varchar(50);not null;comment:生日"`
	Sex      int    `gorm:"column:sex;type:int;not null;comment:性别"`
	Age      int    `gorm:"column:age;type:int;not null;comment:年龄"`
	Status   int    `gorm:"column:status;type:int;not null;comment:状态"`
}

// 通过手机号查询用户信息
func GetUserByMobile(mobile string) (u *User, err error) {
	tx := global.DB.Where("mobile = ?", mobile).Find(&u)
	if tx.RowsAffected != 0 || tx.Error != nil {
		return u, err
	}
	return nil, nil
}

// 用户注册
func (u *User) Register() (*User, error) {
	err := global.DB.Create(&u).Error
	return u, err
}
func GetUserInfo(mobile string) (u *User, err error) {
	tx := global.DB.Where("mobile = ?", mobile).Find(&u)
	if tx.Error != nil {
		return nil, status.Error(codes.Internal, "数据库异常")
	}

	if tx.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "用户列表为空")
	}
	return u, nil
}

// 用户列表
func UserList(page, limit int) (nums int64, users []*User, err error) {
	tx := global.DB.Scopes(pkg.Paginate(page, limit)).Find(&users)
	if tx.Error != nil {
		return 0, nil, status.Error(codes.Internal, "数据库异常")
	}

	if tx.RowsAffected == 0 {
		return 0, nil, status.Error(codes.NotFound, "用户列表为空")
	}
	global.DB.Count(&nums)
	return nums, users, err
}

// 修改用户信息
func (u *User) UpdateUserInfo() error {
	return global.DB.Model(&u).Where("id = ?", u.ID).Updates(&u).Error

}
